<template>
  <component :is="useDrawer ? 'el-drawer' : 'el-dialog'"
             :title="dialogTitle"
             :visible.sync="dialogVisible"
             :size="useDrawer ? '600px' : undefined"
             :width="useDrawer ? undefined : '600px'"
             @close="resetForm"
             destroy-on-close>

    <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">

      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username"></el-input>
      </el-form-item>

      <el-form-item label="姓名" prop="realName">
        <el-input v-model="formData.realName"></el-input>
      </el-form-item>

      <el-form-item label="用户类型" prop="userType">
        <el-radio-group v-model="formData.userType">
          <el-radio :label="0">学生</el-radio>
          <el-radio :label="1">教师</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="班级" prop="orgId">
        <class-select :key="classSelectKey" v-model="formData.orgId" style="width: 100%;"/>
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="formData.gender">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="0">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="formData.mobile"></el-input>
      </el-form-item>

      <el-form-item label="头像" prop="avatar">
        <el-input v-model="formData.avatar"></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password"></el-input>
      </el-form-item>

      <el-form-item label="状态" prop="enabled">
        <el-switch v-model="formData.enabled"/>
      </el-form-item>

    </el-form>

    <div :slot="useDrawer ? 'default' : 'footer'" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </component>
</template>

<script>
import api from '@/common/api';
import Editor from '@/components/admin/Editor';
import ClassSelect from "@/components/admin/ClassSelect.vue";

export default {
  name: 'EditUserDialog',
  props: {
    useDrawer: {
      type: Boolean,
      default: false
    }
  },

  components: {
    Editor,
    ClassSelect
  },

  data() {
    return {
      loading: false,
      dialogVisible: false,
      classSelectKey: 0,

      formData: {
        username: '',
        realName: '',
        password: '',
        userType: null,
        gender: null,
        avatar: '',
        mobile: '',
        faceImg: '',
        enabled: true,
        orgId: []
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
        ],
        realName: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
          {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
        ],
        userType: [
          {required: true, message: '请选择用户类型', trigger: 'blur'}
        ],
        enabled: [
          {required: true, message: '请选择状态', trigger: 'change'}
        ]
      }
    }
  },

  computed: {
    dialogTitle() {
      return this.formData.id ? '编辑用户' : '添加用户'
    }
  },

  methods: {
    async open(data) {
      const formData = {...data}

      // 处理班级信息 - 如果有 classId，通过接口查询完整路径
      if (formData.classId) {
        try {
          const res = await api.admin_getAncestorOrgList({orgId: formData.classId})
          const ancestors = res.data.data || []
          if (ancestors.length > 0) {
            // 精确提取 [学校, 年级, 班级] 对应的 id，兼容存在 校区/机构/学段 等层级
            const school = ancestors.find(o => String(o.orgType) === '3')
            const grade = ancestors.find(o => String(o.orgType) === '6')
            const clazz = ancestors.find(o => String(o.orgType) === '7')
            formData.orgId = [school?.id, grade?.id, clazz?.id]
              .filter(Boolean)
              .map(id => String(id))
          }
        } catch (error) {
          console.error('获取祖先组织失败:', error)
          formData.orgId = []
        }
      } else {
        formData.orgId = []
      }

      // 先设置表单数据，再打开对话框，确保 ClassSelect 初次渲染即可拿到值完成回显
      this.formData = Object.assign({}, this.formData, formData)
      // 强制重新挂载 ClassSelect，避免内部状态缓存导致回显异常
      this.classSelectKey = Date.now()
      this.dialogVisible = true
    },

    resetForm() {
      this.$refs.formRef?.resetFields()
      this.formData = {
        username: '',
        realName: '',
        password: '',
        userType: null,
        gender: null,
        avatar: '',
        mobile: '',
        faceImg: '',
        enabled: true,
        orgId: []
      }
    },

    submitForm() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return

        try {
          this.loading = true
          const formData = {...this.formData}

          // 处理班级信息
          if (formData.orgId && formData.orgId.length > 0) {
            formData.schoolId = formData.orgId[0]
            formData.gradeId = formData.orgId[1]
            formData.classId = formData.orgId[2]
          }
          delete formData.orgId

          // 学生必须选择班级
          if (formData.userType === 0 && !formData.classId) {
            this.$message.warning('请选择班级')
            return
          }

          const {data} = await api.admin_saveOrgUser(formData)
          this.$message.success('保存成功')
          this.dialogVisible = false

          this.$emit('success', data.data)
        } finally {
          this.loading = false
        }
      })
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  padding: 20px;
  text-align: right;
}
</style>
